package cn.signalpha.modules.auth.granter;

import cn.signalpha.core.jwt.JwtUtil;
import cn.signalpha.core.jwt.props.JwtProperties;
import cn.signalpha.core.launch.constant.TokenConstant;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.secure.utils.AuthUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.modules.auth.dto.UserInfo;
import cn.signalpha.modules.auth.enums.UserEnum;
import cn.signalpha.modules.auth.provider.ITokenGranter;
import cn.signalpha.modules.auth.provider.TokenParameter;
import cn.signalpha.modules.auth.utils.TokenUtil;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.shop.service.SellerService;
import cn.signalpha.modules.system.service.IUserService;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * RefreshTokenGranter
 */
@Component
@AllArgsConstructor
public class RefreshTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "refresh_token";

	private final UserService userService;
	private final IUserService sysUserService;
	private final JwtProperties jwtProperties;
	private final SellerService sellerService;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		String grantType = tokenParameter.getArgs().getStr("grantType");
		String refreshToken = tokenParameter.getArgs().getStr("refreshToken");
		UserInfo userInfo = null;
		if (Func.isNoneBlank(grantType, refreshToken) && grantType.equals(TokenConstant.REFRESH_TOKEN)) {
			// 判断令牌合法性
			if (!judgeRefreshToken(grantType, refreshToken)) {
				throw new ServiceException(TokenUtil.TOKEN_NOT_PERMISSION);
			}
			Claims claims = AuthUtil.parseJWT(refreshToken);
			if (claims != null) {
				String tokenType = Func.toStr(claims.get(TokenConstant.TOKEN_TYPE));
				if (tokenType.equals(TokenConstant.REFRESH_TOKEN)) {
					Long userId = Func.toLong(claims.get(TokenConstant.USER_ID));
					String userType = tokenParameter.getArgs().getStr("userType");
					if (userType.equals(UserEnum.WEB.getName())) {
						userInfo = sysUserService.userInfo(userId);
					} else if (userType.equals(UserEnum.WAP.getName())) {
						userInfo = userService.userInfo(userId);
					} else if (userType.equals(UserEnum.SELLER.getName())) {
						userInfo = sellerService.userInfo(userId);
					} else {
						throw new ServiceException("无效的用户类型");
					}
				}
			}
		}
		return userInfo;
	}

	/**
	 * 校验refreshToken合法性
	 *
	 * @param grantType    认证类型
	 * @param refreshToken refreshToken
	 */
	private boolean judgeRefreshToken(String grantType, String refreshToken) {
		if (jwtProperties.getState() && jwtProperties.getSingle()) {
			Claims claims = JwtUtil.parseJWT(refreshToken);
			String tenantId = String.valueOf(claims.get("tenant_id"));
			String clientId = String.valueOf(claims.get("client_id"));
			String userId = String.valueOf(claims.get("user_id"));
			String token = JwtUtil.getRefreshToken(tenantId, clientId, userId, refreshToken);
			return StringUtil.equalsIgnoreCase(token, refreshToken);
		}
		return true;
	}
}
